package org.phnq.babel;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.jar.*;
import org.phnq.babel.log.*;

/**
 * <<Class summary>>
 *
 * @author Patrick Gostovic &lt;&gt;
 * @version $Rev$
 */
public final class Environment
{
	private static Logger log;

	static
	{
		loadEmbeddedNativeLib("phnq_babel");
		log = new Logger(Environment.class);
		log.info("Loaded embedded native library: phnq_babel");
		extractEmbeddedResources();
	}
	
	public static void init()
	{
		// does nothing -- just used to load native lib.
	}
	
	private static void extractEmbeddedResources()
	{
		try
		{
			File embedResDir = File.createTempFile("resources", null);
			embedResDir.delete();
			embedResDir.mkdir();
			embedResDir.deleteOnExit();
			
			addResourcePath(embedResDir.getAbsolutePath());
			
			JarInputStream jarIn = new JarInputStream(Environment.class.getResourceAsStream("/phnq_resources.jar"));
			JarEntry entry;
			int b;
			byte[] buff = new byte[1024];
			while((entry=jarIn.getNextJarEntry())!=null)
			{
				File f = new File(embedResDir, entry.getName());
				if(entry.isDirectory())
				{
					f.mkdirs();
				}
				else
				{
					FileOutputStream out = new FileOutputStream(f);
					while((b=jarIn.read(buff, 0, buff.length)) != -1)
					{
						out.write(buff, 0, b);
					}
					out.close();
				}
				f.deleteOnExit();
			}
			jarIn.close();
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
	}
	
	private static void loadEmbeddedNativeLib(String libName)
	{
		try
		{
			// Copy the embedded native lib to a temp file and load it...
			InputStream in = Environment.class.getResourceAsStream("/"+System.mapLibraryName(libName));
			File f = File.createTempFile(libName, "lib");
			FileOutputStream out = new FileOutputStream(f);
			
			byte[] buff = new byte[1024];
			int b;
			while((b=in.read(buff)) != -1)
			{
				out.write(buff, 0, b);
			}
			in.close();
			out.close();
			
			f.deleteOnExit();
			
			System.load(f.getAbsolutePath());
		}
		catch(IOException ex)
		{
			System.out.println("Error copying embedded native library "+libName+" lib to temp file.");
			ex.printStackTrace();
		}
		catch(UnsatisfiedLinkError err)
		{
			System.out.println("Could not load embedded native library "+libName+".");
			err.printStackTrace();
		}
	}
	
	public static native void addResourcePath(String path);
}
